import React, { Component } from 'react';
import { Button, Form, Icon, Input, Checkbox } from 'antd'
import { withRouter } from 'react-router-dom'
import commonFuc from '../../utils/commonFuc.js'
import titleImg from '.././../assets/img/title.png'
import title1Img from '.././../assets/img/title1.png'

import loginApi from '../../api/login'
import './login.scss'

const FormItem = Form.Item;
class Login extends Component {

    state = {
        isSavePass: true,
        readOnly: false,
        isNeedCode: false,//是否显示验证码
        isSend: false,//是否点击发送验证码按钮
        codeImg: "",
        isAllLogin: true,//是否从登陆中心跳转过来
        loading: false,//登陆按钮加载状态
    }

    // 监听记住密码点击事件
    onSavePassChange = (e) => {
        this.setState({
            isSavePass: e.target.checked
        })
    }

    // 登录
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            this.setState({ loading: true })
            if (!err) {
                loginApi.login(values, (data) => {
                    if (data === true) {
                        //登录成功，跳转页面             
                        this.props.history.push('/');
                        // 存储缓存信息
                        commonFuc.localStorage.setItem("userInfo", {
                            userId: this.props.form.getFieldValue("userId"),
                            passwd: this.state.isSavePass ? this.props.form.getFieldValue("passwd") : '',
                        })
                    } else if (data === false) {
                        //验证码来袭
                        this.setState({
                            isNeedCode: true
                        })
                        this.setState({ loading: false })
                    } else if (data === "loginError") {
                        this.setState({ loading: false })
                    }

                })
                // console.log('Received values of form: ', values);
            }
        });
    }

    //跳转到“忘记密码”页面
    handleToForgetPass = () => {
        this.props.history.push('/forgetPass');
    }

    handleGedCode = () => {
        this.setState({
            isSend: true,
            codeImg: `${process.env.Text[0] == 'https://market.mshiedu.com' ? "https://center.mshiedu.com" : process.env.Text[0]}/center/sys/validateCode?userId=${this.props.form.getFieldValue('userId')}&random=${Math.random()}`
        })

    }

    getQueryString = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = this.props.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }

    componentWillMount() {        
        if (this.getQueryString('token')) {            
            //判断是否从集中登陆中心跳转            
            sessionStorage.setItem('token', this.getQueryString('token'));
            // 获取用户信息
            loginApi.getUserInfo({},res => {
                sessionStorage.setItem('userInfo', JSON.stringify(res));
                this.props.history.push('/');
            })
        }else{
            let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
            let originOrgType = 0//0-旧机构；1-新机构
            if(userInfo){
              originOrgType = userInfo.originOrgType
            }
            // 新机构
            if(originOrgType){
                // saas新慧简学机构域名
                let hostname = window.location.hostname
                if(hostname == 'sys.myunedu.com'){
                  window.location.href = `${window.location.origin}` 
                }else{
                  window.location.href = `${process.env.Text[2]}/?hostname=market`
                }
            }else{
                window.location.href = `${process.env.Text[2]}/?sys=market`
            }
            sessionStorage.removeItem('userInfo')
        }
    }

    componentDidMount() {
        // 获取缓存中的用户信息
        if (!this.state.isAllLogin) {
            this.props.form.setFieldsValue({
                userId: commonFuc.localStorage.getItem("userInfo") ? commonFuc.localStorage.getItem("userInfo").userId : "",
                passwd: commonFuc.localStorage.getItem("userInfo") ? commonFuc.localStorage.getItem("userInfo").passwd : "",
            })
        } else {
            this.setState({
                isAllLogin: false
            })
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const { isNeedCode, codeImg, isSend, isAllLogin, loading } = this.state;
        return null
        if (!isAllLogin) {
            return (
                <div className="login-page">
                    <div className="content_box">
                        <div className="main">
                            <div>
                                <img src={titleImg} alt="" />
                            </div>
                            <div style={{ marginTop: 50 }}>
                                <img src={title1Img} alt="" />
                            </div>
                            <Form onSubmit={this.handleSubmit} className="login-form" style={{ marginTop: 55 }}>
                                <FormItem>
                                    {getFieldDecorator('userId', {
                                        rules: [{ required: true, message: '请填写有效账户' }],
                                    })(
                                        <Input prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="账号" />
                                    )}
                                </FormItem>
                                <FormItem>
                                    {getFieldDecorator('passwd', {
                                        rules: [{ required: true, message: '请输入密码' }],
                                    })(
                                        <Input prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" readOnly={this.state.readOnly} placeholder="密码" />
                                    )}
                                </FormItem>
                                <div className={!isNeedCode ? 'dn' : ''}>
                                    <FormItem >
                                        {getFieldDecorator('validCode')(
                                            <Input className="fl" placeholder="请输入验证码" style={{ width: 210 }} />
                                        )}
                                        <div className="getCodeBox">
                                            <img className={!isSend ? 'dn' : ''} src={codeImg} alt="" />
                                            <Button className={isSend ? 'dn' : ''} type="primary" onClick={this.handleGedCode}>获取验证码</Button>
                                        </div>
                                    </FormItem>
                                </div>
                                <div style={{ marginBottom: 20 }}>
                                    <Checkbox checked={this.state.isSavePass} onChange={this.onSavePassChange}  >记住密码</Checkbox>
                                    <p className="fr forgetPass" onClick={this.handleToForgetPass}>忘记密码</p>
                                </div>
                                <FormItem>
                                    <Button type="primary" htmlType="submit" className="login-form-button" loading={loading} style={{ width: 320 }}>
                                        登&nbsp;&nbsp;录
                                    </Button>
                                </FormItem>
                            </Form>
                        </div>
                    </div>
                    <div className="foot_div">
                        (©) 2017-MSEDU 广东明世教育集团有限公司版权所有 粤ICP备16032470号
                    </div>
                </div>
            )
        } else {
            return null
        }
    }
}
export default withRouter(Form.create()(Login));
// const WrappedNormalLoginForm = withRouter(Form.create()(Login));

// export default WrappedNormalLoginForm;


